<template>
  <el-dialog :title="showTitle" :visible="showDialog" @close="cancel">
    <el-form ref="deptForm" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width: 80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编号" prop="code">
        <el-input v-model="formData.code" style="width: 80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width: 80%" placeholder="请选择" @focus="getEmployeeSimple">
          <el-option v-for="item in peoples" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" type="textarea" :rows="3" style="width: 80%" placeholder="1-300个字符" />
      </el-form-item>
    </el-form>

    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartmentDetail, updateDepartments } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
import { getRequiredRules } from '@/utils/validate'

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    treeNode: {
      type: Object,
      default: null
    }
  },
  data() {
    const checkNameRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.formData.id) {
        // 编辑
        isRepeat = depts.filter(item => item.pid === this.treeNode.pid && item.id !== this.treeNode.id).some(item => item.name === value)
      } else {
        // 添加
        isRepeat = depts.filter(item => item.pid === this.treeNode.id).some(item => item.name === value)
      }
      isRepeat ? callback(new Error('同级部门下已存在该部门')) : callback()
    }
    const checkCodeRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.formData.id) {
        // 编辑
        isRepeat = depts.filter(item => item.id !== this.treeNode.id).some(item => item.code === value && value)
      } else {
        // 添加
        isRepeat = depts.some(item => item.code === value && value)
      }
      isRepeat ? callback(new Error('该编号已被其他部门使用')) : callback()
    }
    return {
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [getRequiredRules('部门名称'),
          { min: 1, max: 50, trigger: 'blur', message: '长度为1-50个字符' },
          { trigger: 'blur', validator: checkNameRepeat }],
        code: [getRequiredRules('部门编号'),
          { min: 1, max: 50, trigger: 'blur', message: '长度为1-50个字符' },
          { trigger: 'blur', validator: checkCodeRepeat }],
        manager: [getRequiredRules('部门负责人'),
          { min: 1, max: 300, trigger: 'blur', message: '长度为1-300个字符' }],
        introduce: [getRequiredRules('部门介绍'),
          { min: 1, max: 50, trigger: 'blur', message: '长度为1-50个字符' }]
      },
      peoples: []
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑部门' : '添加子部门'
    }
  },
  methods: {
    async getEmployeeSimple() {
      this.peoples = await getEmployeeSimple()
    },
    async getDepartmentDetail(id) {
      // 由于props传值是异步的，不能直接使用treeNode.id
      this.formData = await getDepartmentDetail(id)
      // console.log(this.formData)
    },
    submit() {
      this.$refs.deptForm.validate(async isOk => {
        if (isOk) {
          if (this.formData.id) {
            // 编辑部门
            await updateDepartments(this.formData)
          } else {
            // 添加部门
            await addDepartments({ ...this.formData, pid: this.treeNode.id })
          }
          // 告诉父页面，使其重新渲染
          this.$emit('addDepts')
          // .sync修饰符，动态修改传递过来的showDialog
          this.$emit('update:showDialog', false)
          // 这里会触发el-dialog的close事件
        }
      })
    },
    cancel() {
      // reset只能重置表单上的数据，编辑时传入的id不能重置，因此需要手动重置
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      this.$emit('update:showDialog', false)
      this.$refs.deptForm.resetFields()
    }
  }
}
</script>

<style>
.el-dialog__header {
  background-color: #3d6df8;
}
</style>
